import ColorUISdk from '../../mp-sdk/index'

const sdk = new ColorUISdk({
  env: 'dev',
  version: '1.0.0',
  api: {
    dev: { 
      url: 'http://172.20.10.2:5000' // 后端实际地址（从login.ts复制）
    }
  }
})

Page({
  data: {
    phone: '',
    code: '',
    password: '',
    countdown: 0
  },

  onPhoneChange(e: any) {
    this.setData({
      phone: e.detail.value
    })
  },

  onCodeChange(e: any) {
    this.setData({
      code: e.detail.value
    })
  },

  onPasswordChange(e: any) {
    this.setData({
      password: e.detail.value
    })
  },

  async getVerificationCode() {
    const { phone } = this.data
    
    if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }
    
    try {
      // 调用获取验证码接口
      const res = await sdk.request({
        url: '/auth/send-code',
        method: 'POST',
        data: { phone }
      })
      
      if (res.code === 0) {
        wx.showToast({
          title: '验证码已发送',
          icon: 'none'
        })
        
        // 开始倒计时
        let countdown = 60
        this.setData({ countdown })
        
        const timer = setInterval(() => {
          countdown--
          this.setData({ countdown })
          
          if (countdown <= 0) {
            clearInterval(timer)
          }
        }, 1000)
      } else {
        wx.showToast({
          title: res.msg || '获取验证码失败',
          icon: 'none'
        })
      }
    } catch (error) {
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      })
    }
  },

  async register() {
    const { phone, code, password } = this.data
    
    if (!phone || !code || !password) {
      wx.showToast({
        title: '请完善信息',
        icon: 'none'
      })
      return
    }
    
    if (password.length < 6) {
      wx.showToast({
        title: '密码长度不能少于6位',
        icon: 'none'
      })
      return
    }
    
    try {
      wx.showLoading({ title: '注册中...' })
      
      const res = await sdk.request({
        url: '/auth/register',
        method: 'POST',
        data: { phone, code, password }
      })
      
      wx.hideLoading()
      
      if (res.code === 0) {
        wx.showToast({
          title: '注册成功',
          icon: 'success'
        })
        
        // 注册成功后跳转到登录页
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showToast({
          title: res.msg || '注册失败',
          icon: 'none'
        })
      }
    } catch (error) {
      wx.hideLoading()
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      })
    }
  }
})